#!/usr/bin/python
# encoding: utf-8
# Licensed under the Apache License, Version 2.0 (the "License");
# you may not use this file except in compliance with the License.
# You may obtain a copy of the License at
# 
#      http://www.apache.org/licenses/LICENSE-2.0
# 
# Unless required by applicable law or agreed to in writing, software
# distributed under the License is distributed on an "AS IS" BASIS,
# WITHOUT WARRANTIES OR CONDITIONS OF ANY KIND, either express or implied.
# See the License for the specific language governing permissions and
# limitations under the License.
"""
launchapp

Created by Greg Neagle on 2010-02-05.
Modified 2010-07-13 to pass all arguments to /usr/bin/open
Launches an app only if we're called in the current
GUI user's session.
Prevents multiple copies of the app from being launched
when Fast User Switching is in use
Intended for use by a launchd LaunchAgent.
"""

import sys
import os
import subprocess
import time


def getconsoleuser():
    '''Uses Apple's SystemConfiguration framework to get the current
    console user'''
    from SystemConfiguration import SCDynamicStoreCopyConsoleUser
    cfuser = SCDynamicStoreCopyConsoleUser( None, None, None )
    return cfuser[0]


def main():
    '''Pass arguments to /usr/bin/open only if we are the current
    console user or no user and we're at the login window'''
    consoleuser = getconsoleuser()
    try:
        thisuser = os.environ['USER']
    except KeyError:
        # when run via launchd at loginwindow context, os.environ['USER']
        # is undefined, so we'll return root (the effective user)
        thisuser = "root"
        
    if (consoleuser == thisuser) or \
        (consoleuser == None and thisuser == "root"):
        cmd = ["/usr/bin/open"]
        if len(sys.argv) > 1:
            cmd.extend(sys.argv[1:])
        else:
            print >> sys.stderr, "Must specify an app to launch!"
            exit(-1)
        retcode = subprocess.call(cmd)
        # sleep 10 secs to make launchd happy
        time.sleep(10)
        exit(retcode)
    else:
        # we aren't in the current GUI session
        # sleep 10 secs to make launchd happy
        time.sleep(10)
        exit(0)
    

if __name__ == '__main__':
    main()

